/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef CONFIG_MANAGER_H
#define CONFIG_MANAGER_H

#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <functional>
#include <mutex>
#include "nlohmann/json.hpp"
#include "utils_callback_list.h"

namespace El {
namespace Common {

// 配置处理优先级定义
enum class ConfigPriority : int32_t {
    VERIFY = 0,      // 配置校验阶段
    APPLY = 100,     // 配置应用阶段
    POST_APPLY = 200 // 配置应用后阶段
};

class ConfigManager {

    ConfigManager();
    ~ConfigManager();

public:
    static ConfigManager &GetInstance();

    bool LoadConfig(const std::string &filename, const std::string &defaultConfigFilename);

    nlohmann::json GetConfig(const std::string &path);
    bool SetConfig(const std::string &path, const nlohmann::json &value, bool notify = true);

    nlohmann::json GetDefaultConfig(const std::string &path);
    // 递归设置默认配置，检查每一项是否存在，不存在则设置默认值
    bool SetDefaultConfig(const std::string &path, const nlohmann::json &value);

    // 出厂重置方法
    bool ResetToFactory();

    int32_t Register(const std::string &path,
                     std::function<bool(const nlohmann::json &)> listener,
                     ConfigPriority priority = ConfigPriority::POST_APPLY);
    void Unregister(const std::string &path, int32_t listenerId);

private:
    // 获取路径的所有父路径
    std::vector<std::string> GetParentPaths(const std::string &path);

    bool NotifyListeners(const std::string &path, const nlohmann::json &value);
    void MergeConfigs(const nlohmann::json &defaultConfig);
    bool LoadConfig(const std::string &filename, nlohmann::json &value);
    bool SaveConfig(const std::string &filename, const nlohmann::json &config);
    
    // 递归合并JSON对象，深度合并默认值
    void RecursiveMergeDefaults(nlohmann::json &target, const nlohmann::json &defaults);

private:
    std::mutex mutex_;
    nlohmann::json defaultConfig_;
    nlohmann::json config_;
    std::map<std::string, Utils::CallbackList<bool, const nlohmann::json &>> listeners_;
    std::string filename_;
    std::string defaultFilename_;
};

} // namespace Common
} // namespace El

#endif // CONFIG_MANAGER_H
